package com.ywgt.controller;


import com.github.pagehelper.Page;
import com.ywgt.pojo.Issue;
import com.ywgt.service.IssueService;
import com.ywgt.util.ResponseUtil;
import io.swagger.annotations.ApiModel;
import org.hamcrest.core.Is;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("/admin/issue")
@ApiModel("通用问题管理")
public class IssueController {

    @Autowired
    IssueService issueService;

    /**
     *  page: 1,
     *         limit: 20,
     *         question: undefined,
     *         sort: 'add_time',
     *         order: 'desc'
     * @return
     */
    @GetMapping("/list")
    public Object getIssues(String question,@RequestParam(required = false,defaultValue = "add_time") String sort,
                            @RequestParam(required = false,defaultValue = "desc") String order,
                            @RequestParam(required = false,defaultValue = "1") int page,
                            @RequestParam(required = false,defaultValue = "10") int limit){
        Page<Issue> issues=issueService.getIssues(question,page,limit,sort,order);
        List<Issue> items = issues.getResult().stream().filter(issue -> !issue.getDeleted()).collect(Collectors.toList());
        long total = issues.getTotal();
        Map<String,Object> data=new HashMap<>();
        data.put("total",total);
        data.put("items",items);
        return ResponseUtil.ok(data);
    }

    @PostMapping("/update")
    public Object update(@RequestBody Issue issue){
        if(issueService.updateById(issue)){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }
    @PostMapping("/delete")
    public Object delete(@RequestBody Issue issue){
        if(issueService.removeById(issue.getId())){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }

    @PostMapping("/create")
    public Object create(@RequestBody Issue issue){
        if(issueService.save(issue)){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }
}
